package com.klm.datakeeper.filemonitoring;

import java.io.File;
import java.util.ArrayList;

import com.dropbox.sync.android.DbxAccountManager;
import com.dropbox.sync.android.DbxException.Unauthorized;
import com.dropbox.sync.android.DbxFileSystem;
import com.klm.datakeeper.AppConstants;
import com.klm.datakeeper.DbxApiAppConstants;

import android.app.Service;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Binder;
import android.os.Environment;
import android.os.IBinder;
import android.util.Log;
import android.widget.Toast;

public class FileModificationService extends Service{


	private static final String DEFAULT_MONITORING_FILE_PATH = "/DataKeeper/";
	private final IBinder iBinder = new FileModificationServiceBinder();
	private DbxFileSystem dbxFileSystem;
	private ArrayList<FilePathObserver> filePathObserversList;
	private SharedPreferences filePathsObserverPreferences;
	private SharedPreferences.Editor filePathsObserverPreferencesEditor;
	
	@Override
	public void onCreate() {
		if (!EnvironmentUtilsStatic.isExternalStorageAvailable()) {
			Toast.makeText(FileModificationService.this, "SDCARD is not available!", Toast.LENGTH_SHORT).show();
			return;
		}
		
		filePathObserversList = new ArrayList<FilePathObserver>();
		
		try {
			dbxFileSystem = DbxFileSystem.forAccount(DbxAccountManager
					.getInstance(getApplicationContext(),
							DbxApiAppConstants.APP_KEY,
							DbxApiAppConstants.APP_SECRET).getLinkedAccount());
		} catch (Unauthorized e) {
			e.printStackTrace();
		}
		
		filePathsObserverPreferences = getSharedPreferences(AppConstants.FILE_PATHS_OBSERVER_PREFERENCES, MODE_PRIVATE);
		filePathsObserverPreferencesEditor = filePathsObserverPreferences.edit();
		
		String defaultFolderPath = Environment.getExternalStorageDirectory().getPath() + DEFAULT_MONITORING_FILE_PATH;
		if(!filePathsObserverPreferences.contains(AppConstants.FILE_PATH_PREFS_KEY + 0)){
			filePathsObserverPreferencesEditor.putString(
					AppConstants.FILE_PATH_PREFS_KEY + 0,
					defaultFolderPath
					);
			File defaultFolder = new File(Environment.getExternalStorageDirectory(), DEFAULT_MONITORING_FILE_PATH);
			if(!defaultFolder.exists())
				if(defaultFolder.mkdirs())
					Log.d(getClass().getSimpleName(), "default folder " + defaultFolderPath + " was created");
			filePathsObserverPreferencesEditor.commit();
		} 
		
	}
	
	public FilePathObserver createFileObserver(File file) {
		
		
		if (!file.isDirectory()) {
			FilePathObserver filePathObserver = new FilePathObserver(file.getAbsolutePath(), dbxFileSystem, this);
			filePathObserversList.add(filePathObserver);
			return filePathObserver;
		} else {
			FilePathObserver filePathObserver = new FilePathObserver(file.getAbsolutePath(), dbxFileSystem, this);
			filePathObserversList.add(filePathObserver);
			try {
				for (File currentFile : file.listFiles()) {
					createFileObserver(currentFile);
				}
			} catch (Exception e) {
				Log.e("Error", e.toString());
			}
			return filePathObserver;
		}
	}
	
	@Override
	public void onStart(Intent intent, int startid) {
		
		filePathObserversList.clear();
		
		int i = 0;
		while(filePathsObserverPreferences.getString(AppConstants.FILE_PATH_PREFS_KEY + i, null) != null){
			createFileObserver(new File(filePathsObserverPreferences.getString(AppConstants.FILE_PATH_PREFS_KEY + i, null)));
			i++;
		}
		
		for(FilePathObserver filePathObserver : filePathObserversList)
			filePathObserver.startWatching();
		
		Toast.makeText(this.getApplicationContext(), "start monitoring file modification", Toast.LENGTH_SHORT).show();
	}

	@Override
	public void onDestroy() {
		for(FilePathObserver filePathObserver : filePathObserversList)
			filePathObserver.stopWatching();
		Toast.makeText(this.getApplicationContext(), "stop monitoring file modification", Toast.LENGTH_SHORT).show();
	}

	@Override
	public IBinder onBind(Intent arg0) {
		return iBinder;
	}
	
	public ArrayList<FilePathObserver> getFilePathObserversList() {
		return filePathObserversList;
	}
	
	public class FileModificationServiceBinder extends Binder{
		
		public FileModificationService getService(){
			return FileModificationService.this;
		}
		
	}
}
